package sdk

import (
	"crypto/md5"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/spf13/cast"
	"io/ioutil"
	"net/http"
	"net/url"
	time2 "time"
)

//小米渠道上报接口
func ReportApiEmi(imei string, clientIp string) error {
	//根据文档填写必填参数
	//注意！设备信息必须按照文档顺序填写否则会sign校验失败
	device := []pair{
		{"imei", imei},
		{"oaid", imei},
		{"conv_time", cast.ToString(time2.Now().UnixMilli())},
		{"client_ip", clientIp},
		{"ua", "Dalvik/2.1.0 (Linux; U; Android 11; M2012K11AC Build/RKQ1.200826.002)"},
	}
	appId := "1511611"
	convType := "APP_REGISTER"
	customerId := "336982"
	finalInfo := buildInfo(device, "ERHpHltayMRfxbtG", "snnEIMxqqjJaICPA")
	finalUrl := fmt.Sprintf("http://trail.e.mi.com/global/log?appId=%s&info=%s&conv_type=%s&customer_id=%s", appId, finalInfo, convType, customerId)
	resp, err := http.Get(finalUrl)
	if err != nil {
		return err
	}
	s1, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(s1, resp)
	if err != nil {
		return err
	}
	fmt.Println(string(s1))
	defer resp.Body.Close()
	return nil
}

type pair struct {
	key   string
	value string
}

func buildInfo(device []pair, signKey string, encryptKey string) string {
	//queryString 设备信息
	query := ""
	for i, p := range device {
		and := ""
		if i != 0 {
			and = "&"
		}
		query += fmt.Sprintf("%s%s=%s", and, p.key, p.value)
	}
	query1 := url.QueryEscape(query)
	//md5后的sign值
	sign := fmt.Sprintf("%x", md5.Sum([]byte(signKey+"&"+query1)))
	//baseData
	baseData := query + "&sign=" + sign
	return enc(baseData, encryptKey)
}

//对baseData进行加密 Base64(simple_xor{base_data, encrypt_key})
func enc(baseData string, key string) string {
	l2 := len(key)
	var res []byte
	for i := range baseData {
		u := baseData[i] ^ key[i%l2]&0xFF
		res = append(res, u)
	}
	return url.QueryEscape(base64.StdEncoding.EncodeToString(res))
}
